package com.example.test.advice.第三章_类_对象_方法.建议43_避免对象的浅拷贝;

public class CopyClient {

    public static void main(String[] args) throws CloneNotSupportedException {
        //定义父亲
        Person father = new Person("父亲");
        //定义大儿子
        Person son1 = new Person("大儿子",father);
        //小儿子的信息是通过大儿子拷贝过来的
        Person son2 = son1.clone();
        son2.setName("小儿子");

        //大儿子认个干爹
        son1.getFather().setName("干爹");
        System.out.println(son1.getName()+" 的父亲是"+son1.getFather().getName());
        System.out.println(son2.getName()+" 的父亲是"+son2.getFather().getName());

    }
}

class Person implements Cloneable{
    //姓名
    private String name;
    //父亲
    private Person Father;

    public Person(String name) {
        this.name = name;
    }

    public Person(String name, Person father) {
        this.name = name;
        Father = father;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Person getFather() {
        return Father;
    }

    public void setFather(Person father) {
        Father = father;
    }

    @Override
    protected Person clone() throws CloneNotSupportedException {
        Person person = null;
        try {
            person = (Person) super.clone();
            person.setFather(new Person(person.getFather().getName()));//增加此行实现深拷贝
        }catch (Exception e){
            e.printStackTrace();
        }
        return person;
    }
}